
import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, Animated, View, Image, TextInput, Platform, TouchableOpacity
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import moment from 'moment';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { STORAGE_CONSTANT } from '../../../config/storage';
import StorageHelper from '../../../utils/storageHelper';
import Dictionary from '../../../utils/dictionary';
import { style } from '../../../theme/style';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ResourceListItemCard } from './_components/resourceListItemCard';
import { RangTime } from '../../../component/common/RangTime.js';
import { OfferCommon } from '../_common/common';

const scale = GLOBAL.SCALE;
const selectIcon = require('../../../imgs/select.png')
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const addIcon = require('../../../imgs/plus.png');

export class OfferList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			companyIndex: 0,
			tabIndex: 0,
			tabItem: 0,
			status: 'loading',
			refreshIcon: false,
			listData: [],
			itemData: {},
			totalPage: '0',
			isModal: false,
			typesIndex: 0,
			statusIndex: 0,
			options: [],
			choice: {},
			alertShow: false
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1;
		const { salesType } = props.navigation.state.params;
		this.pageParams = {
			pageNo: 1,
			pageSize: 10,
			beginDate: moment(moment().subtract(1, 'months').calendar()).format('YYYY-MM-DD') || null, //默认展示近一个月
			endDate: moment().format('YYYY-MM-DD') || null,
			bizModel: '',
			status: '',
			salesType: salesType || 'P',
			corpId: ''
		}
		that = this;
	}

	static navigationOptions = ({ navigation, navigationOptions }) => {
		let { salesType } = navigation.state.params || {};

		return {
			headerTitle: (salesType == 'S' ? '销售' : '采购') + '资源发布列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: <Common type="headRight" rightText={'新增'} tintColor='#fff' rightIcon={addIcon} color='#fff'
				onPress={() => {
					let { choice } = that.state;
					let { corpId } = choice || {};
					navigation.navigate('OfferCreatePage', { salesType, corpId });
				}} />,
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	getDict = async () => {
		this.offerTypeData = await Dictionary.get('CRM_RULE_BIZ_MODEL') || [];  // 报盘类型
		this.offerTypeData = this.offerTypeData.filter(item => item.dictKey != "OT");
		this.offerTypeData.unshift({
			dictName: '全部类型',
			dictKey: ''
		})
	}

	async getSorage() {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
	}

	//初始化数据
	initPage = async (refreshIcon) => {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		this.pageParams.corpId = this.state.choice.corpId;
		let res = await HTTP.POST(API_GENERATE(API.PACKAGE_APPLY_PERIOD), this.pageParams);

		if (res) {
			res = this.getRequireParams(res);
			this.setState({
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				status: res.rows.length > 0 ? 'data' : 'empty',
				refreshIcon: false,
				totalPage: res.totalPage,
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}
	// 返回值数据补充
	getRequireParams = (res) => {
		if (res.rows && res.rows.length > 0) {
			res.rows.forEach(item => {
				item.showItem = false;
				item.boxHeight = new Animated.Value(item.packageApplyPeriodGoodsListTOS && item.packageApplyPeriodGoodsListTOS.length >= 2 ? 112 * scale : 66 * scale);
				item.openHeight = 0;
				if (item.packageApplyPeriodGoodsListTOS && item.packageApplyPeriodGoodsListTOS.length > 0) {
					item.openHeight = 66 * item.packageApplyPeriodGoodsListTOS.length
				} else {
					item.packageApplyPeriodGoodsListTOS = []
				}
			})
		}
		return res
	}

	loadMore = () => {
		if (this.state.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	refresh = () => {
		this.pageParams.pageNo = 1;
		if (this.state.totalPage >= this.pageParams.pageNo) {
			this.reload = false;
			this.initPage();
		}
	}

	onErrorRefresh = () => {
		let { tabIndex } = this.state;
		if (tabIndex != 2) {
			this.initPage();
		}
	}

	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 选择时间
	_resultCall = (resultData) => {
		this.pageParams.beginDate = resultData.startTime || '';
		this.pageParams.endDate = resultData.endTime || '';
		this.setState({
			showTimeModal: false
		}, () => {
			this.reloadPage()
		})
	}

	//回调
	_selectCallBack = (index) => {
		let { selectType, typesIndex, statusIndex, typesSelectText, statusSelectText } = this.state;
		// selectType===1 取状态；selectType===0 取类型
		this.setState({
			isModal: false,
			typesIndex: selectType ? typesIndex : index,
			statusIndex: selectType ? index : statusIndex,
			statusSelectText: selectType ? OfferCommon.OFFER_STATUS_LIST[index].dictName : statusSelectText,
			typesSelectText: selectType ? typesSelectText : this.offerTypeData[index].dictName,
		}, () => {
			this.pageParams.status = OfferCommon.OFFER_STATUS_LIST[this.state.statusIndex].dictKey;
			this.pageParams.bizModel = this.offerTypeData[this.state.typesIndex].dictKey;
			this.reloadPage();
		})
	}

	//切换功能
	_toggle = (onoff) => {
		this.setState({
			isModal: onoff
		})
	}
	_approvalListItim = (data) => {
		let { listData, choice } = this.state;
		let { salesType, firstbidPackageApplyId } = data.item || {};
		let { corpId } = choice || {};
		return (
			<View key={data.index}>
				<ResourceListItemCard
					itemData={data}
					listData={listData}
					copyPress={() => { navigationSeevice.navigate('OfferCreatePage', { salesType, bidPackageApplyId: firstbidPackageApplyId, corpId, isCopy: true }) }}
					itemPress={() => { navigationSeevice.navigate('OfferApproveDetail', { pageFrom: 'resource', data: data.item, salesType }) }}
					resetListData={(resetListData) => {
						this.setState({ listData: resetListData })
					}} />
			</View>
		)
	}

	render() {
		let { listData, refreshIcon, status, showTimeModal, statusSelectText, typesSelectText, typesIndex, statusIndex,
			selectType, isModal, choice, options, alertShow } = this.state;
		let { beginDate, endDate } = this.pageParams;
		return (
			<View style={styles.container}>
				<NavigationEvents onWillFocus={async () => {
					await this.getDict();
					await this.getSorage();
					await this.reloadPage();
				}} />
				<View style={styles.headerWrap}>
					<View style={styles.searchView}>
						<View style={{ flex: 1 }}>
							<Image source={searchIcon} style={styles.searchIcon} />
							<TextInput
								ref="enterpriseInput"
								style={styles.searchInput}
								underlineColorAndroid='transparent'
								placeholder={"请输入查询内容"}
								placeholderTextColor="rgba(255, 255, 255, .8)"
								maxLength={30}
								returnKeyType={'search'}
								defaultValue={this.pageParams.searchKey}
								onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
								onSubmitEditing={() => { this.reloadPage(); }}
							/>
						</View>
						{
							options.length > 1 ?
								<View style={styles.searchSelect}>
									<NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} accountStyles={{ paddingRight: 0 }} />
								</View> : null
						}
					</View>
				</View>
				<View style={styles.statusSelect}>
					<TouchableOpacity style={styles.statusItem} onPress={() => {
						this.setState({ isModal: true, selectType: 1 })
					}}>
						<Text style={styles.statusSelectText}>{statusSelectText || '全部状态'}</Text>
						<Image style={styles.statusSelectIcon} source={selectIcon} />
					</TouchableOpacity>
					<TouchableOpacity style={styles.statusItem} onPress={() => {
						this.setState({ isModal: true, selectType: 0 })
					}}>
						<Text style={styles.statusSelectText}>{typesSelectText || '全部类型'}</Text>
						<Image style={styles.statusSelectIcon} source={selectIcon} />
					</TouchableOpacity>
					<TouchableOpacity activeOpacity={.8} style={styles.dateWrap} onPress={() => {
						this.setState({
							showTimeModal: true,
							showStatusSelect: false,
						})
					}}>
						<View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
							<View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
								<Text style={styles.dateText}>{beginDate || '开始时间'}</Text>
								<Text style={styles.dateText}>{endDate || '结束时间'}</Text>
							</View>
							<Image style={styles.statusSelectIcon} source={selectIcon} />
						</View>
					</TouchableOpacity>
				</View>
				{
					status == 'data' ? (
						(
							<View style={styles.body}>
								<FlatList
									data={listData}
									renderItem={this._approvalListItim}
									refreshing={refreshIcon}
									onEndReachedThreshold={1}
									showsVerticalScrollIndicator={false}
									onRefresh={() => { this.refresh() }}
									onEndReached={() => { this.loadMore() }}
								/>
							</View>
						)
					) : (<View style={{ flex: 1 }}>
						<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
					</View>)
				}

				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={selectType ? statusIndex : typesIndex} title={selectType ? '资源状态' : '报盘类型'} listData={selectType ? OfferCommon.OFFER_STATUS_LIST : this.offerTypeData} selectCallBack={this._selectCallBack} />
				)} isVisible={isModal} closeCallballFn={() => { this._toggle(false) }} />

				{
					showTimeModal ?
						<RangTime isVisible={true} markedDates={null}
							startTime={this.pageParams.beginDate}
							endTime={this.pageParams.endDate}
							closeCall={() => { this.setState({ showTimeModal: false }) }}
							resultCall={this._resultCall} /> : null
				}

				{
					options.length ? <SlideSelect alertShow={alertShow} options={options}
						select={(val) => {
							this.setState({ choice: val || options[0], alertShow: false }, () => {
								this.initPage();
							})
						}}
						unselect={() => {
							this.setState({ alertShow: false })
						}} /> : null
				}
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	body: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	itemBorder: {
		height: 1 * scale,
		backgroundColor: '#E3E7F0',
		marginBottom: 15 * scale,
	},
	arrowIcon: {
		position: 'absolute',
		right: 0,
		top: 2 * scale,
		right: 32 * scale,
	},
	textRow: {
		marginBottom: 20 * scale
	},
	textRowText: {
		paddingLeft: 15 * scale
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingBottom: 34 * scale,
	},
	searchView: {
		marginTop: 5 * scale,
		marginLeft: 20 * scale,
		marginRight: 20 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
	},
	searchIcon: {
		width: 20 * scale,
		height: 20 * scale,
		position: 'absolute',
		left: 32 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	searchInput: {
		height: 36 * scale,
		// width: 226 * scale,
		paddingLeft: 62 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .38)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 6 * scale,
		color: '#fff',
	},
	searchSelect: {
		marginLeft: 18 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end'
	},
	searchSelectText: {
		fontSize: 13 * scale,
		fontWeight: 'bold',
		marginRight: 4 * scale,
		color: '#fff'
	},
	searchSelectIcon: {
		width: 12 * scale,
		height: 6 * scale,
		tintColor: '#fff'
	},
	statusSelect: {
		backgroundColor: '#fff',
		marginTop: -20 * scale,
		marginLeft: 20 * scale,
		marginRight: 20 * scale,
		padding: 16 * scale,
		borderRadius: 6 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	statusSelectText: {
		fontSize: 13 * scale,
		marginRight: 4 * scale,
		color: style.color.themeColor
	},
	statusSelectIcon: {
		width: 12 * scale,
		height: 6 * scale,
		tintColor: style.color.themeColor
	},
	dateWrap: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
	},
	dateText: {
		fontSize: 13 * scale,
		fontWeight: 'bold',
		marginRight: 4 * scale,
		color: style.color.themeColor
	},
	statusItem: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'flex-start',
		alignItems: 'center',
		flexWrap: 'wrap'
	}
})